//
//  DCFLoginManager.m
//  DCF
//
//  Created by 吴文拼 on 2017/12/26.
//  Copyright © 2017年 吴文拼. All rights reserved.
//

#import "DCFLoginManager.h"
#import "DCFNetworkManager.h"

#define UserInfoFilePath [NSString stringWithFormat:@"%@/%@", PATH_OF_DOCUMENT, @"userInfo"]

@implementation DCFLoginManager

static DCFUserModel *loginUserModel = nil;

+ (instancetype)sharedInstance
{
    static DCFLoginManager *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[DCFLoginManager alloc] init];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if ([fileManager fileExistsAtPath:UserInfoFilePath]) {
            NSDictionary *userInfo = [NSDictionary dictionaryWithContentsOfFile:UserInfoFilePath];
            loginUserModel = [[DCFUserModel alloc] initWithDic:userInfo];
        }
    });
    
    return instance;
}

- (void)saveLoginUserModelInfo:(DCFUserModel *)model{
    NSDictionary *dict = [model getJsonDic];
    NSMutableDictionary *mutDic = [dict mutableCopy];
    NSMutableArray *deleteArr = [NSMutableArray array];
    for (NSString *keyStr in mutDic.allKeys) {
        if ([[mutDic objectForKey:keyStr] isEqual:[NSNull null]]) {
            [deleteArr addObject:keyStr];
        }
    }
    for (NSString *keyStr in deleteArr) {
        [mutDic removeObjectForKey:keyStr];
    }
    [self clearUserInfo];
    BOOL result = [[mutDic copy] writeToFile:UserInfoFilePath atomically:YES];
    if (!result) {
        NSLog(@"%@", @"保存用户登录信息到本地文件失败");
    }else{
        loginUserModel = model;
    }
}

- (void)clearUserInfo{
    NSFileManager * fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:UserInfoFilePath]) {
        [fileManager removeItemAtPath:UserInfoFilePath error:nil];
    }
    loginUserModel = nil;
}

- (DCFUserModel *)currentUser{
    return loginUserModel;
}

- (NSInteger)uid
{
    if (!loginUserModel)
    {
        return 0;
    }
    return [loginUserModel.userId integerValue];
}

- (BOOL)isLogin{
    if (loginUserModel) {
        return YES;
    }
    return NO;
}

-(void)logoutWithCompleteBlock:(void (^)(BOOL))completeBlock{
    [self clearUserInfo];
    if (completeBlock) {
        completeBlock(YES);
    }
}


@end
